package cn.edu.cuit.filter;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <h1>演示要点：拦截或放行</h1>
 * <li>1 正常登录，会有session对象
 * <li>2 为空登录，不会有session对象
 * <li>3 用firefox or chrome直接访问admin/index.jsp会弹出未登录【过滤器发生作用】
 * <li>4 登录后，再直接访问admin/index.jsp，有session存在，不用重新登录
 * <li>5 关闭浏览器或是换一个浏览器，没有session了，将被过滤
 * 
 * @author fhzheng
 *
 */

public class LoginFilter implements Filter {

	private FilterConfig config = null;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 防中文乱码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 获取session对象
		HttpSession session = ((HttpServletRequest) request).getSession();
		// 查看session中有无需要的值 
		if (session.getAttribute("user") == null) {
			// 没有值，拦截则跳转到/login/login.jsp页
			// 特别要注意当前所在目录和路径
			PrintWriter out = response.getWriter();
			// 直接向客户端输出js脚本动作
			out.print("<script language = javascript>alert('您还没有登录！！！');window.location.href='../login/login.jsp'</script>");
		} else {
			// 如果有值，则直接放行
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
	}

	/**
	 * Constructor of the object.
	 */
	public LoginFilter() {
		super();
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

}
